﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using DVDFilmoteka.Forms;
using DVDFilmoteka.ServerDatabaseManagement;
using MovieStorage;
using DVDFilmoteka.Settings;
using System.Net;
using System.IO;
using System.Drawing;

namespace DVDFilmoteka.Forms
{
    public partial class FindAllForm : LocalizableForm
    {
        private readonly List<MovieDataStore12> filmList;
        private readonly EServerDatabases server;        
        private readonly MainForm parentForm;
        private readonly Boolean findAll;
        private int count;

        private readonly List<FindAllReport> report;

        public delegate void IncProgressBar();
        public IncProgressBar incProgressBar;

        public delegate void MaxProgressBar(Int32 max);
        public MaxProgressBar maxProgressBar;

        public delegate void SetLabelText(String text);
        public SetLabelText setLabelText;

        public FindAllForm(List<MovieDataStore12> filmList, EServerDatabases server, MainForm parentForm, Boolean findAll)
        {
            InitializeComponent();

            this.filmList = filmList;
            this.server = server;
            this.parentForm = parentForm;
            this.findAll = findAll;

            incProgressBar = IncProgressBarMethod;
            maxProgressBar = MaxProgressBarMethod;
            setLabelText = SetLabelTextMethod;

            report = new List<FindAllReport>(filmList.Count);
        }

        private void IncProgressBarMethod()
        {
            if (progressBar1.Maximum > progressBar1.Value+1) progressBar1.Value++;
        }

        private void MaxProgressBarMethod(Int32 max)
        {
            progressBar1.Maximum = max;
            progressBar1.Value = 0;
        }

        private void SetLabelTextMethod(String text)
        {
            labelSearching.Text = text;
        }

        private List<MovieDataStore12> FindAll()
        {
            IServerDatabase serverDatabase = ServerDatabaseFactory.getInstance(server);
            if (serverDatabase == null) return filmList;

            List<MovieDataStore12> newList = new List<MovieDataStore12>();

            String serverHodnoceni = "";
            String serverSign = "";
            if (server == EServerDatabases.CSFD) serverSign = "csfd";
            if (server == EServerDatabases.IMDB) serverSign = "imdb";
            // Spocitat kolik filmu se bude vyhledavat            
            foreach (MovieDataStore12 item in filmList)
            {
                if (server == EServerDatabases.CSFD) serverHodnoceni = item.csfdRating;
                if (server == EServerDatabases.IMDB) serverHodnoceni = item.imdbRating;

                if (string.IsNullOrEmpty(serverHodnoceni) || findAll)
                {
                    count++;
                }
            }
            Invoke(maxProgressBar, new object[] { count });

            // Vyhledat filmy
            foreach (MovieDataStore12 item in filmList)
            {
                Boolean isAlreadyFound = true;
                String filmName = "";
                // Zjistit na jakem serveru hledame
                if (server == EServerDatabases.CSFD)
                {
                    serverHodnoceni = item.csfdRating;
                    filmName = item.czechName;
                    if (String.IsNullOrEmpty(filmName)) filmName = item.originalName;
                }
                if (server == EServerDatabases.IMDB)
                {
                    serverHodnoceni = item.imdbRating;
                    filmName = item.originalName;
                    if (String.IsNullOrEmpty(filmName)) filmName = item.czechName;
                }

                MovieDataStore12 updatedFilmData = null;

                // Chybi vyplneny link
                if (!item.link.ToLower().Contains(serverSign))
                {
                    isAlreadyFound = false;
                    if (!String.IsNullOrEmpty(filmName))
                    {
                        Invoke(setLabelText, new object[] { String.Format(Properties.Messages.form_findall_labelSearching, filmName) });
                        try
                        {
                            updatedFilmData = serverDatabase.getFilmData(filmName);
                        } catch (Exception) {}
                        Invoke(incProgressBar, new object[] { });
                    }
                }
                else if (string.IsNullOrEmpty(serverHodnoceni) || findAll) //Je vyplneny link, ale neni vyplnene hodnoceni
                {
                    isAlreadyFound = false;
                    String[] linkList = item.link.Split(' ');
                    String link = "";
                    foreach (String it in linkList)
                    {
                        if (it.ToLower().Contains(serverSign))
                        {
                            link = it;
                            break;
                        }
                    }

                    Invoke(setLabelText, new object[] { String.Format(Properties.Messages.form_findall_labelSearching, link) });
                    try
                    {
                        updatedFilmData = serverDatabase.getFilmDataFromLink(link);
                    } catch (Exception) {}
                    Invoke(incProgressBar, new object[] { });
                }

                MovieDataStore12 returnFilmData = (MovieDataStore12)item.Clone();
                FindAllReport returnReport = new FindAllReport();

                // Upravit zaznam novymi daty nalezenymi v databazi
                if (updatedFilmData != null)
                {
                    if (!SettingsManager.Instance.Data.DontChangeGenres && updatedFilmData.otherGenre != null && updatedFilmData.otherGenre.Count > 0) returnFilmData.otherGenre = updatedFilmData.otherGenre;
                    if (!SettingsManager.Instance.Data.DontChangeGenres && !String.IsNullOrEmpty(updatedFilmData.mainGenre)) returnFilmData.mainGenre = updatedFilmData.mainGenre;
                    if (!String.IsNullOrEmpty(updatedFilmData.csfdRating)) returnFilmData.csfdRating = updatedFilmData.csfdRating;
                    if (!String.IsNullOrEmpty(updatedFilmData.imdbRating)) returnFilmData.imdbRating = updatedFilmData.imdbRating;
                    if ((!SettingsManager.Instance.Data.DontChangeNames || String.IsNullOrEmpty(returnFilmData.czechName)) && !String.IsNullOrEmpty(updatedFilmData.czechName)) returnFilmData.czechName = updatedFilmData.czechName;
                    if ((!SettingsManager.Instance.Data.DontChangeNames || String.IsNullOrEmpty(returnFilmData.originalName)) && !String.IsNullOrEmpty(updatedFilmData.originalName)) returnFilmData.originalName = updatedFilmData.originalName;
                    if (!String.IsNullOrEmpty(updatedFilmData.link)) returnFilmData.link = parentForm.addLink(returnFilmData.link, updatedFilmData.link);

                    if (updatedFilmData.actors != null) returnFilmData.actors = updatedFilmData.actors;
                    if (!String.IsNullOrEmpty(updatedFilmData.country)) returnFilmData.country = updatedFilmData.country;
                    if (!String.IsNullOrEmpty(updatedFilmData.length)) returnFilmData.length = updatedFilmData.length;
                    if (!String.IsNullOrEmpty(updatedFilmData.recenze)) returnFilmData.recenze = updatedFilmData.recenze;
                    if (!String.IsNullOrEmpty(updatedFilmData.year)) returnFilmData.year = updatedFilmData.year;
                    if (!String.IsNullOrEmpty(updatedFilmData.directorName)) returnFilmData.directorName = updatedFilmData.directorName;
                    if (!String.IsNullOrEmpty(updatedFilmData.directorLink)) returnFilmData.directorLink = updatedFilmData.directorLink;

                    if (!String.IsNullOrEmpty(updatedFilmData.pictureLink))
                    {
                        returnFilmData.pictureLink = updatedFilmData.pictureLink;
                        if (!SettingsManager.Instance.Data.LoadPicturesOnline)
                        {
                            WebClient client = new WebClient();
                            if (!SettingsManager.Instance.Data.UseDefaultProxy)
                            {
                                WebProxy proxy = new WebProxy(SettingsManager.Instance.Data.ProxyIPAddress.ToString(),
                                                              SettingsManager.Instance.Data.ProxyPort);
                                client.Proxy = proxy;
                            }
                            else
                            {
                                client.Proxy = WebRequest.GetSystemWebProxy();
                            }

                            byte[] data = client.DownloadData(returnFilmData.pictureLink); // Nacist obrazek z netu
                            if (data != null)
                            {
                                returnFilmData.pictureData = Convert.ToBase64String(data); // Ulozit v Base64
                            }
                            else
                            {
                                returnFilmData.pictureData = "";                                
                            }
                        }
                        else
                        {
                            returnFilmData.pictureData = "";
                        }
                    }

                    // Nastavit polozky uspesneho reportu
                    returnReport.Succesfull = true;
                    returnReport.NewOriginalName = updatedFilmData.originalName;
                    returnReport.NewCzechName = updatedFilmData.czechName;
                    returnReport.OldOriginalName = item.originalName;
                    returnReport.OldCzechName = item.czechName;
                } 
                else
                {
                    // Nastavit polozky neuspesneho reportu
                    returnReport.Succesfull = false;
                    returnReport.NewOriginalName = "";
                    returnReport.NewCzechName = "";
                    returnReport.OldOriginalName = item.originalName;
                    returnReport.OldCzechName = item.czechName;
                }

                if (!isAlreadyFound) report.Add(returnReport);
                newList.Add(returnFilmData);
            }

            return newList;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            Close();
        }

        private void FindAllForm_Load(object sender, EventArgs e)
        {
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.RunWorkerAsync();           
        }



        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = FindAll();
            }
            catch (Exception)
            {
                e.Result = null;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                parentForm.vyhledatVšechnyComplete((List<MovieDataStore12>)e.Result, report, count > 0);
            }

            Close();
        }

        public override void Localize()
        {
            this.Text = Properties.Messages.form_findall_text;
            labelSearching.Text = String.Format(Properties.Messages.form_findall_labelSearching, "");
            buttonStop.Text = Properties.Messages.form_findall_buttonStop;
        }
    }
}